using AForge.Video.FFMPEG;
using Clancy.Common;
using System;
using System.Drawing;
using System.Threading.Tasks;

namespace Clancy.Bl.VideoProvider
{
    internal class VideoFilePropertyProvider : IDisposable
    {
        private readonly long m_FrameCount;
        private readonly float m_FrameRate;
        private readonly VideoFileReader m_VideoReader;

        public VideoFilePropertyProvider(string filepath)
        {
            m_VideoReader = new VideoFileReader();
            m_VideoReader.Open(filepath);
            m_FrameRate = m_VideoReader.FrameRate;
            m_FrameCount = m_VideoReader.FrameCount;
        }

        public TimeSpan Duration
        {
            get { return TimeSpan.FromSeconds(m_FrameCount / m_FrameRate); }
        }

        public double FrameRate
        {
            get { return m_FrameRate; }
        }

        public void Dispose()
        {
            m_VideoReader.Close();
            m_VideoReader.Dispose();
        }

        public Task<byte[]> GetThumbnailIconAsJpegByteArray(TimeSpan thumbSourceTime)
        {
            double targetFrame = thumbSourceTime.TotalSeconds * FrameRate;

            int count = 0;
            Bitmap thumbnailFrame = null;
            do
            {
                if (thumbnailFrame != null)
                {
                    thumbnailFrame.Dispose();
                }
                thumbnailFrame = m_VideoReader.ReadVideoFrame();
                count++;
            } while (count <= targetFrame);

            if (thumbnailFrame != null)
            {
                byte[] data = thumbnailFrame.ToJpegByteArray();
                thumbnailFrame.Dispose();

                return Task.FromResult(data);
            }
            return Task.FromResult(new byte[] { });
        }
    }
}